<template>
  <div class="tab-content h-full">
    <!-- 有活动标签页时显示内容 -->
    <div v-if="activeTab" class="tab-content-wrapper h-full">
      <keep-alive>
        <component 
          :is="getTabComponent(activeTab.type)"
          :key="activeTab.id"
          :tab="activeTab"
          @update="handleTabUpdate"
        />
      </keep-alive>
    </div>

    <!-- 没有标签页时显示欢迎页面 -->
    <!-- <div v-else class="welcome-page">
      <div class="welcome-content">
        <div class="welcome-header">
          <div class="welcome-logo">
            <el-icon class="text-6xl text-blue-500 mb-4"><Coin /></el-icon>
          </div>
          <h1 class="welcome-title">欢迎使用 Database Manager</h1>
          <p class="welcome-subtitle">专业的数据库管理工具</p>
        </div>

        <div class="welcome-actions">
          <div class="action-grid">
            <div class="action-card" @click="createNewQuery">
              <el-icon class="action-icon"><Document /></el-icon>
              <h3 class="action-title">新建查询</h3>
              <p class="action-desc">创建SQL查询并执行</p>
            </div>

            <div class="action-card" @click="createNewConnection">
              <el-icon class="action-icon"><Plus /></el-icon>
              <h3 class="action-title">新建连接</h3>
              <p class="action-desc">添加数据库连接</p>
            </div>

            <div class="action-card" @click="openRecentQueries">
              <el-icon class="action-icon"><Clock /></el-icon>
              <h3 class="action-title">最近查询</h3>
              <p class="action-desc">查看查询历史</p>
            </div>

            <div class="action-card" @click="openSettings">
              <el-icon class="action-icon"><Setting /></el-icon>
              <h3 class="action-title">设置</h3>
              <p class="action-desc">配置应用设置</p>
            </div>
          </div>
        </div>

        <div class="welcome-footer">
          <div class="quick-stats">
            <div class="stat-item">
              <span class="stat-label">连接数</span>
              <span class="stat-value">{{ connectionCount }}</span>
            </div>
            <div class="stat-item">
              <span class="stat-label">查询历史</span>
              <span class="stat-value">{{ queryHistoryCount }}</span>
            </div>
            <div class="stat-item">
              <span class="stat-label">活动连接</span>
              <span class="stat-value">{{ activeConnectionCount }}</span>
            </div>
          </div>

          <div class="recent-connections" v-if="recentConnections.length > 0">
            <h4 class="recent-title">最近使用的连接</h4>
            <div class="recent-list">
              <div
                v-for="connection in recentConnections"
                :key="connection.id"
                class="recent-item"
                @click="connectToDatabase(connection)"
              >
                <el-icon class="recent-icon">
                  <component :is="getConnectionIcon(connection)" />
                </el-icon>
                <div class="recent-info">
                  <div class="recent-name">{{ connection.name }}</div>
                  <div class="recent-type">{{ getConnectionTypeLabel(connection.type) }}</div>
                </div>
                <div :class="['recent-status', getConnectionStatusClass(connection)]"></div>
              </div>
            </div>
          </div>
        </div>
      </div>
    </div> -->
  </div>
</template>

<script setup>
import { ref, computed, markRaw } from 'vue'
import { useRouter } from 'vue-router'
import { useTabStore, useConnectionStore, useDatabaseStore } from '@/stores'
import { DatabaseTypes } from '@/services/database'
import QueryEditor from './QueryEditor.vue'
import DataBrowser from './DataBrowser.vue'
import TableDesignerV2 from './TableDesignerV2.vue'
import ConnectionManager from './ConnectionManager.vue'
import TablesBrowserTab from '../tabs/TablesBrowserTab.vue'
import { ElMessageBox } from 'element-plus'

// 组件映射
const componentMap = {
  'table': markRaw(DataBrowser),
  'browse': markRaw(DataBrowser),
  'query': markRaw(QueryEditor),
  'design': markRaw(TableDesignerV2),
  'tablesBrowser': markRaw(TablesBrowserTab),
  'connection': markRaw(ConnectionManager)
}

const router = useRouter()
const tabStore = useTabStore()
const connectionStore = useConnectionStore()
const databaseStore = useDatabaseStore()

// 计算属性
const activeTab = computed(() => {
  return tabStore.activeTab
})

const connectionCount = computed(() => {
  return connectionStore.connections.length
})

const queryHistoryCount = computed(() => {
  return databaseStore.queryHistory.length
})

const activeConnectionCount = computed(() => {
  return connectionStore.connectedConnections.length
})

const recentConnections = computed(() => {
  return connectionStore.connections
    .slice()
    .sort((a, b) => new Date(b.lastUsed || 0) - new Date(a.lastUsed || 0))
    .slice(0, 5)
})

// 方法 - 使用防抖避免频繁更新
let updateTimeout = null
const handleTabUpdate = (updates) => {
  if (updateTimeout) {
    clearTimeout(updateTimeout)
  }
  
  updateTimeout = setTimeout(() => {
  if (activeTab.value) {
    tabStore.updateTab(activeTab.value.id, updates)
  }
  }, 100) // 100ms防抖
}

const createNewQuery = () => {
  const connectionId = connectionStore.activeConnectionId
  if (connectionId) {
    tabStore.createQueryTab(connectionId)
  } else if (connectionStore.connections.length > 0) {
    // 如果有连接但没有激活的，使用第一个连接
    tabStore.createQueryTab(connectionStore.connections[0].id)
  } else {
    ElMessage.warning('请先创建数据库连接')
    createNewConnection()
  }
}

const createNewConnection = () => {
  // 触发新建连接对话框
  // 这里应该通过事件或者store来触发
  ElMessage.info('请在左侧连接浏览器中点击"+"按钮创建新连接')
}

const openRecentQueries = () => {
  // 创建查询历史标签页或者显示查询历史面板
  ElMessage.info('查询历史功能开发中...')
}

const openSettings = () => {
  router.push('/settings')
}

const connectToDatabase = async (connection) => {
  try {
    await connectionStore.connectToDatabase(connection.id)
    ElMessage.success(`已连接到 ${connection.name}`)
  } catch (error) {
    ElMessage.error(`连接失败: ${error.message}`)
  }
}

const getConnectionIcon = (connection) => {
  const iconMap = {
    [DatabaseTypes.MYSQL]: 'Coin',
    [DatabaseTypes.POSTGRESQL]: 'Coin',
    [DatabaseTypes.SQLITE]: 'Document',
    [DatabaseTypes.SQLSERVER]: 'Coin'
  }
  return iconMap[connection.type] || 'Coin'
}

const getConnectionTypeLabel = (type) => {
  const labels = {
    [DatabaseTypes.MYSQL]: 'MySQL',
    [DatabaseTypes.POSTGRESQL]: 'PostgreSQL',
    [DatabaseTypes.SQLITE]: 'SQLite',
    [DatabaseTypes.SQLSERVER]: 'SQL Server'
  }
  return labels[type] || type
}

const getConnectionStatusClass = (connection) => {
  const status = connectionStore.getConnectionStatus(connection.id)
  if (status.isConnected) {
    return 'connected'
  } else if (status.connecting) {
    return 'connecting'
  } else {
    return 'disconnected'
  }
}

// 根据标签页类型获取对应组件
const getTabComponent = (type) => {
  return componentMap[type] || markRaw(QueryEditor)
}
</script>

<style scoped>
.tab-content {
  background: #ffffff;
}

.tab-content-wrapper {
  position: relative;
}

.unknown-tab-type {
  display: flex;
  align-items: center;
  justify-content: center;
  height: 100%;
}

/* 欢迎页面样式 */
.welcome-page {
  display: flex;
  align-items: center;
  justify-content: center;
  height: 100%;
  background: linear-gradient(135deg, #667eea 0%, #764ba2 100%);
  color: white;
  overflow-y: auto;
}

.welcome-content {
  max-width: 1000px;
  width: 100%;
  padding: 2rem;
  text-align: center;
}

.welcome-header {
  margin-bottom: 3rem;
}

.welcome-title {
  font-size: 2.5rem;
  font-weight: 700;
  margin-bottom: 0.5rem;
  background: linear-gradient(45deg, #ffffff, #e0e7ff);
  -webkit-background-clip: text;
  -webkit-text-fill-color: transparent;
  background-clip: text;
}

.welcome-subtitle {
  font-size: 1.2rem;
  opacity: 0.9;
  margin-bottom: 0;
}

.welcome-actions {
  margin-bottom: 3rem;
}

.action-grid {
  display: grid;
  grid-template-columns: repeat(auto-fit, minmax(200px, 1fr));
  gap: 1.5rem;
  max-width: 800px;
  margin: 0 auto;
}

.action-card {
  background: rgba(255, 255, 255, 0.1);
  backdrop-filter: blur(10px);
  border: 1px solid rgba(255, 255, 255, 0.2);
  border-radius: 12px;
  padding: 2rem 1.5rem;
  cursor: pointer;
  transition: all 0.3s ease;
}

.action-card:hover {
  background: rgba(255, 255, 255, 0.2);
  transform: translateY(-4px);
  box-shadow: 0 8px 32px rgba(0, 0, 0, 0.2);
}

.action-icon {
  font-size: 2.5rem;
  margin-bottom: 1rem;
  color: #e0e7ff;
}

.action-title {
  font-size: 1.2rem;
  font-weight: 600;
  margin-bottom: 0.5rem;
}

.action-desc {
  font-size: 0.9rem;
  opacity: 0.8;
  margin: 0;
}

.welcome-footer {
  display: grid;
  grid-template-columns: 1fr 2fr;
  gap: 2rem;
  align-items: start;
}

.quick-stats {
  display: flex;
  justify-content: space-around;
  background: rgba(255, 255, 255, 0.1);
  backdrop-filter: blur(10px);
  border-radius: 12px;
  padding: 1.5rem;
}

.stat-item {
  text-align: center;
}

.stat-label {
  display: block;
  font-size: 0.9rem;
  opacity: 0.8;
  margin-bottom: 0.5rem;
}

.stat-value {
  display: block;
  font-size: 1.5rem;
  font-weight: 700;
  color: #e0e7ff;
}

.recent-connections {
  background: rgba(255, 255, 255, 0.1);
  backdrop-filter: blur(10px);
  border-radius: 12px;
  padding: 1.5rem;
  text-align: left;
}

.recent-title {
  font-size: 1.1rem;
  font-weight: 600;
  margin-bottom: 1rem;
  color: #e0e7ff;
}

.recent-list {
  space-y: 0.5rem;
}

.recent-item {
  display: flex;
  align-items: center;
  padding: 0.75rem;
  border-radius: 8px;
  cursor: pointer;
  transition: background-color 0.2s ease;
}

.recent-item:hover {
  background: rgba(255, 255, 255, 0.1);
}

.recent-icon {
  font-size: 1.2rem;
  margin-right: 0.75rem;
  color: #e0e7ff;
}

.recent-info {
  flex: 1;
}

.recent-name {
  font-weight: 500;
  margin-bottom: 0.25rem;
}

.recent-type {
  font-size: 0.8rem;
  opacity: 0.8;
}

.recent-status {
  width: 8px;
  height: 8px;
  border-radius: 50%;
  margin-left: 0.5rem;
}

.recent-status.connected {
  background-color: #10b981;
  box-shadow: 0 0 0 2px rgba(16, 185, 129, 0.3);
}

.recent-status.disconnected {
  background-color: #ef4444;
  box-shadow: 0 0 0 2px rgba(239, 68, 68, 0.3);
}

.recent-status.connecting {
  background-color: #f59e0b;
  box-shadow: 0 0 0 2px rgba(245, 158, 11, 0.3);
  animation: pulse 2s infinite;
}

/* 响应式设计 */
@media (max-width: 768px) {
  .welcome-content {
    padding: 1rem;
  }
  
  .welcome-title {
    font-size: 2rem;
  }
  
  .action-grid {
    grid-template-columns: 1fr;
    gap: 1rem;
  }
  
  .welcome-footer {
    grid-template-columns: 1fr;
    gap: 1rem;
  }
  
  .quick-stats {
    flex-direction: column;
    gap: 1rem;
  }
}

@keyframes pulse {
  0%, 100% {
    opacity: 1;
  }
  50% {
    opacity: 0.5;
  }
}
</style> 